import { getRecordDetail } from '@/services/mz'
import { getRecordDetail as getZYRecordDetail } from '@/services/zy'
import { useEffect, useState } from 'react'
import type { TreeDataNode } from 'antd';
import { STATUS_CODE } from '@/common/const'

const isBL = (type) => type === 'bl'
const revertData = (itemArr, type) => {
    return itemArr.map((item) => {
        const isDailyRecord = item.children?.length // 是否是住院日常记录
        const isDir = item.children?.length;
        return {
            key: isBL(type) ? isDailyRecord ? 'te' + item.templateId : item.blId : item.id || item.name,  // 这里要特殊处理日常住院病历
            title: isBL(type) ? (item.templateName || item.name) : item.name,
            url: item.url || '',
            children: item.children ? revertData(item.children, type) : [],
            type,
            canEdit: !isDailyRecord,
            selectable: isBL(type) || !isDir, // 只有非病历的文件夹不允许选中 当前项是否可点击选中
            isDir: isDir,  // 检验结果有文件夹概念，因此增加字段判断是否为文件夹
            createJnumber: item.createJnumber || ''
        }
    })
}
export default (id, type) => {
    const [loading, setLoading] = useState(false)
    const [treeData, setTreeData] = useState<TreeDataNode[]>([])
    const recordDetailApi = type === 'mz' ? getRecordDetail : getZYRecordDetail
    const getData = async () => {
        setLoading(true)
        const { code, data } = await recordDetailApi({ recordId: id })
        if (code === STATUS_CODE.SUCCESS) {
            let treeData: TreeDataNode[] = []
            if (data.bl?.length) {
                treeData.push({
                    title: '病历',
                    key: '0-0',
                    selectable: false,
                    children: revertData(data.bl, 'bl')
                })
            }
            if (data.jyjg.length) {
                treeData.push({
                    title: '检验结果',
                    key: '0-1',
                    selectable: false,
                    children: revertData(data.jyjg, 'img')
                })
            }
            setTreeData(treeData)
        }
        setLoading(false)
    }

    useEffect(() => {
        getData()
    }, [])

    const refresh = () => {
        getData()
    }
    return {
        treeData,
        loading,
        refresh
    }
}